package com.example.mysharding.algo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.api.sharding.complex.ComplexKeysShardingValue;
import org.springframework.util.CollectionUtils;

import java.util.Collection;
import java.util.Objects;
import java.util.Set;


/**
 * @author ：wangzihan6
 * @description：Id和timeRange分片算法
 * @date ：2023/10/10 1:58 下午
 */
@Slf4j
@Data
@AllArgsConstructor
public class ComplexAlgoAdaptor extends BaseShardingIdAndTimeComplexAlgo {

    private String tableName;
    private String shardingIdKey;
    private String[] shardingTimeKeys;
    private Integer dataSourceSize;
    private String dsStartegyClass;

    @Override
    public Collection<String> doSharding(Collection<String> targetNames,
                                         ComplexKeysShardingValue<String> complexKeysShardingValue) {
        if (CollectionUtils.isEmpty(targetNames)) {
            log.error("ComplexAlgo: targetNames is null");
            return null;
        }

        String shardingTimeKey = "";
        Set<String> keySet = complexKeysShardingValue.getColumnNameAndRangeValuesMap().keySet();
        if (!CollectionUtils.isEmpty(keySet) && (Objects.nonNull(shardingTimeKeys) && shardingTimeKeys.length > 0)) {
            for (String key : shardingTimeKeys) {
                if (keySet.contains(key)) {
                    shardingTimeKey = key;
                }
            }
        }

        Collection<String> result = super.baseDoSharding(tableName, shardingIdKey, shardingTimeKey, targetNames,
                complexKeysShardingValue, dataSourceSize, dsStartegyClass);
        return !CollectionUtils.isEmpty(result) ? result : targetNames;
    }
}
